{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "73bd968b-d970-4a05-94ef-4e7abf990827",
   "metadata": {},
   "source": [
    "Chapter 14\n",
    "\n",
    "# 斐波那契数列\n",
    "Book_3《数学要素》 | 鸢尾花书：从加减乘除到机器学习 (第二版)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9518a62e-6d72-4d77-b6c7-f210be3b5aff",
   "metadata": {},
   "source": [
    "这段代码的核心功能是生成并显示斐波那契数列的前 $n$ 项。斐波那契数列的定义是：\n",
    "\n",
    "$$\n",
    "F(0) = 0, \\quad F(1) = 1\n",
    "$$\n",
    "\n",
    "对于 $n \\geq 2$ 的情况，数列的递推关系为：\n",
    "\n",
    "$$\n",
    "F(n) = F(n-1) + F(n-2)\n",
    "$$\n",
    "\n",
    "每一项等于前两项之和，从而形成一系列逐步递增的值。代码中的函数 `fib(n)` 是递归地定义的，用于计算第 $n$ 项的值。递归关系表示，如果 $n \\leq 1$，函数直接返回 $n$；否则，它会调用自身来计算前两项 $F(n-1)$ 和 $F(n-2)$，并返回它们的和。这种递归调用直到到达基准条件，即 $F(0)$ 或 $F(1)$，从而逐步回溯并计算最终结果。\n",
    "\n",
    "在主程序中，定义了变量 `n = 10`，表示我们希望显示数列的前 $10$ 项。然后，代码通过 `for` 循环依次计算每一项 $F(i)$，从 $i = 0$ 到 $i = 9$，并打印输出。这段代码的结果是输出斐波那契数列的前 $10$ 项，通过逐项调用 `fib(i)` 函数并显示计算结果。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85c1aae2-7f61-4f09-b193-8567ae2946ce",
   "metadata": {},
   "source": [
    "## 定义斐波那契数列生成函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d15d8d04-e0ee-48d9-85f0-d910263dd962",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib(n):\n",
    "    # 计算斐波那契数列第n项\n",
    "    if n <= 1:\n",
    "        return (n)  # 如果n小于等于1，返回n\n",
    "    else:\n",
    "        return (fib(n-1) + fib(n-2))  # 否则递归计算前两项之和"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cda79a3c-5f7a-4fe8-9c7a-85b488586c85",
   "metadata": {},
   "source": [
    "## 输出斐波那契数列的前n项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "13119ff3-f4ae-4846-94b1-674f97bbeaba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n"
     ]
    }
   ],
   "source": [
    "n = 10  # 设定要显示的项数\n",
    "for i in range(n):\n",
    "    print(fib(i))  # 打印斐波那契数列的第i项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85a80909-2aac-49ed-bb7a-f8cc6b80ee7d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecd322f4-f919-4be2-adc3-69d28ef25e69",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
